#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
智慧童话世界 - 增强版AI可选分支剧情童话书应用
基于ERNIE-4.5-0.3B-Paddle + 智源研究院数据 + MCP协议
"""

import os
import json
import random
import time
import logging
from datetime import datetime
from flask import Flask, render_template, request, jsonify, session
import secrets

# 导入高级集成模块
try:
    from advanced_ernie_integration import AdvancedERNIEIntegration
    from enhanced_mcp_integration import EnhancedMCPIntegration
    from enhanced_zhiyuan_integration import EnhancedZhiyuanIntegration
    ADVANCED_MODE = True
    print("✅ 高级集成模块加载成功")
except ImportError as e:
    print(f"⚠️ 高级模块加载失败，使用基础模式: {e}")
    ADVANCED_MODE = False

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 初始化Flask应用
app = Flask(__name__)
app.secret_key = secrets.token_hex(16)

class EnhancedFairyTaleGenerator:
    """增强版童话生成器"""
    
    def __init__(self):
        # 初始化高级集成组件
        if ADVANCED_MODE:
            try:
                self.ernie_integration = AdvancedERNIEIntegration()
                self.mcp_integration = EnhancedMCPIntegration()
                self.zhiyuan_integration = EnhancedZhiyuanIntegration()
                
                # 初始化组件
                self.ernie_integration.initialize_model()
                self.mcp_integration.initialize_mcp_client()
                self.zhiyuan_integration.initialize_knowledge_base()
                
                logger.info("✅ 所有高级组件初始化完成")
                self.advanced_ready = True
            except Exception as e:
                logger.error(f"❌ 高级组件初始化失败: {e}")
                self.advanced_ready = False
        else:
            self.advanced_ready = False
        self.story_templates = {
            "勇敢与友谊": {
                "opening": "在一个阳光明媚的早晨，{name}遇到了一个需要帮助的小动物...",
                "themes": ["勇气", "友谊", "互助", "成长"],
                "characters": ["小兔子", "小松鼠", "小鸟", "小熊"],
                "settings": ["森林", "花园", "小溪边", "山坡上"]
            },
            "神奇的森林": {
                "opening": "{name}走进了一片神奇的森林，这里的树木会说话，花朵会唱歌...",
                "themes": ["探索", "好奇心", "自然", "魔法"],
                "characters": ["智慧老树", "彩虹蝴蝶", "会说话的花", "森林精灵"],
                "settings": ["魔法森林", "彩虹桥", "水晶洞穴", "星光草地"]
            },
            "海底探险": {
                "opening": "{name}戴上神奇的潜水镜，潜入了美丽的海底世界...",
                "themes": ["探险", "勇敢", "海洋保护", "友谊"],
                "characters": ["小海豚", "章鱼博士", "海龟爷爷", "珊瑚公主"],
                "settings": ["珊瑚礁", "海底城堡", "深海峡谷", "海藻森林"]
            },
            "太空旅行": {
                "opening": "{name}坐上了闪闪发光的宇宙飞船，开始了奇妙的太空之旅...",
                "themes": ["科学", "探索", "想象力", "友谊"],
                "characters": ["外星朋友", "机器人助手", "星球守护者", "彗星精灵"],
                "settings": ["月球基地", "彩色星球", "星云隧道", "太空站"]
            },
            "动物王国": {
                "opening": "在遥远的动物王国里，{name}被选为了和平大使...",
                "themes": ["和谐", "理解", "保护动物", "责任"],
                "characters": ["狮子国王", "智慧猫头鹰", "活泼猴子", "温柔大象"],
                "settings": ["王宫", "草原", "丛林", "湖泊"]
            }
        }
        
        self.age_adaptations = {
            "3-5岁": {
                "vocabulary": "简单",
                "sentence_length": "短句",
                "complexity": "基础",
                "moral": "简单道理"
            },
            "6-8岁": {
                "vocabulary": "适中",
                "sentence_length": "中等",
                "complexity": "适中",
                "moral": "品德教育"
            },
            "9-12岁": {
                "vocabulary": "丰富",
                "sentence_length": "复杂",
                "complexity": "深入",
                "moral": "深度思考"
            }
        }
        
        # 智源研究院教育数据模拟
        self.zhiyuan_education_data = {
            "认知发展": {
                "3-5岁": ["具象思维", "模仿学习", "情感认知"],
                "6-8岁": ["逻辑思维萌芽", "规则意识", "社交技能"],
                "9-12岁": ["抽象思维", "批判思维", "价值观形成"]
            },
            "教育价值": {
                "勇敢": "培养面对困难的勇气和坚持不懈的精神",
                "友谊": "学会关爱他人，建立良好的人际关系",
                "探索": "激发好奇心和求知欲，培养科学精神",
                "责任": "培养责任感和使命感，成为有担当的人"
            }
        }

    def generate_story(self, name, age, theme, interests):
        """生成个性化童话故事"""
        if self.advanced_ready:
            return self._generate_advanced_story(name, age, theme, interests)
        else:
            return self._generate_basic_story(name, age, theme, interests)
    
    def _generate_advanced_story(self, name, age, theme, interests):
        """使用高级AI生成故事"""
        try:
            # 构建用户画像
            user_profile = {
                "name": name,
                "age_group": age,
                "interests": [i.strip() for i in interests.split(',') if i.strip()],
                "theme_preference": theme,
                "learning_style": "interactive",
                "current_session": datetime.now().isoformat()
            }
            
            # 获取智源研究院个性化内容
            personalized_content = self.zhiyuan_integration.get_personalized_content(user_profile)
            
            # 使用ERNIE生成故事内容
            story_prompt = f"为{age}年龄段的{name}创作一个关于{theme}的互动童话故事，兴趣爱好包括：{interests}"
            story_result = self.ernie_integration.generate_story_content(
                prompt=story_prompt,
                user_profile=user_profile,
                content_framework=personalized_content.get("personalized_framework", {})
            )
            
            # 通过MCP协议优化内容
            optimized_content = self.mcp_integration.optimize_story_content(story_result)
            
            # 生成高级选择分支
            advanced_choices = self.mcp_integration.generate_smart_choices(
                story_context=optimized_content,
                user_profile=user_profile,
                educational_goals=personalized_content.get("educational_goals", [])
            )
            
            return {
                "story": optimized_content.get("story_text", ""),
                "choices": advanced_choices,
                "educational_value": optimized_content.get("educational_themes", []),
                "cognitive_level": personalized_content.get("cognitive_level", []),
                "personalization": personalized_content.get("recommendations", []),
                "ai_insights": optimized_content.get("ai_insights", {}),
                "advanced_mode": True
            }
            
        except Exception as e:
            logger.error(f"高级故事生成失败，回退到基础模式: {e}")
            return self._generate_basic_story(name, age, theme, interests)
    
    def _generate_basic_story(self, name, age, theme, interests):
        """基础故事生成"""
        template = self.story_templates.get(theme, self.story_templates["勇敢与友谊"])
        age_adaptation = self.age_adaptations.get(age, self.age_adaptations["6-8岁"])
        
        # 基于智源数据的教育价值融入
        cognitive_level = self.zhiyuan_education_data["认知发展"][age]
        
        # 生成故事开头
        opening = template["opening"].format(name=name)
        
        # 根据兴趣爱好调整故事元素
        interests_list = [i.strip() for i in interests.split(',') if i.strip()]
        selected_characters = random.sample(template["characters"], min(2, len(template["characters"])))
        selected_setting = random.choice(template["settings"])
        
        # 构建完整故事
        story = f"""
        📖 **{name}的{theme}故事**
        
        {opening}
        
        在{selected_setting}，{name}遇到了{selected_characters[0]}。{selected_characters[0]}看起来很着急，原来是{selected_characters[1]}遇到了困难！
        
        {name}想起了妈妈说过的话："帮助别人就是帮助自己。"于是{name}决定...
        """
        
        # 生成选择分支
        choices = self.generate_choices(theme, age, cognitive_level)
        
        return {
            "story": story,
            "choices": choices,
            "educational_value": template["themes"],
            "cognitive_level": cognitive_level,
            "advanced_mode": False
        }
    
    def generate_choices(self, theme, age, cognitive_level):
        """生成选择分支"""
        base_choices = {
            "勇敢与友谊": [
                "立即上前帮助，不管有什么困难",
                "先了解情况，然后想办法帮助",
                "寻找其他朋友一起来帮忙"
            ],
            "神奇的森林": [
                "跟随神奇的光芒探索更深处",
                "和森林里的动物交朋友",
                "学习森林的魔法知识"
            ],
            "海底探险": [
                "游向更深的海底探险",
                "帮助海洋动物解决问题",
                "收集美丽的海底宝藏"
            ],
            "太空旅行": [
                "访问神秘的外星球",
                "和外星朋友学习科学知识",
                "帮助修复太空站"
            ],
            "动物王国": [
                "组织动物们开会讨论",
                "亲自去了解每个动物的需求",
                "制定保护动物的计划"
            ]
        }
        
        choices = base_choices.get(theme, base_choices["勇敢与友谊"])
        
        # 根据年龄调整选择复杂度
        if age == "3-5岁":
            return choices[:2]  # 简化选择
        elif age == "6-8岁":
            return choices[:3]  # 标准选择
        else:
            return choices + ["想出一个创新的解决方案"]  # 增加创新选择
    
    def continue_story(self, previous_story, choice, context):
        """根据选择继续故事"""
        if self.advanced_ready:
            return self._continue_advanced_story(previous_story, choice, context)
        else:
            return self._continue_basic_story(previous_story, choice, context)
    
    def _continue_advanced_story(self, previous_story, choice, context):
        """使用高级AI继续故事"""
        try:
            # 构建故事上下文
            story_context = {
                "previous_story": previous_story,
                "user_choice": choice,
                "user_context": context,
                "story_history": context.get('story_history', [])
            }
            
            # 使用ERNIE生成故事续集
            continuation_result = self.ernie_integration.continue_story_with_choice(
                story_context=story_context,
                choice_index=choice
            )
            
            # 通过MCP优化续集内容
            optimized_continuation = self.mcp_integration.optimize_story_continuation(
                continuation_result,
                story_context
            )
            
            # 生成智能化的下一步选择
            next_choices = self.mcp_integration.generate_contextual_choices(
                current_story=optimized_continuation.get("story_text", ""),
                user_profile=context,
                story_progression=optimized_continuation.get("progression_analysis", {})
            )
            
            return {
                "story": optimized_continuation.get("story_text", ""),
                "choices": next_choices,
                "story_progress": optimized_continuation.get("progress_status", "continuing"),
                "ai_analysis": optimized_continuation.get("story_analysis", {}),
                "educational_insights": optimized_continuation.get("educational_insights", []),
                "advanced_mode": True
            }
            
        except Exception as e:
            logger.error(f"高级故事续集生成失败，回退到基础模式: {e}")
            return self._continue_basic_story(previous_story, choice, context)
    
    def _continue_basic_story(self, previous_story, choice, context):
        """基础故事续集生成"""
        name = context.get('name', '小朋友')
        theme = context.get('theme', '勇敢与友谊')
        
        # 根据选择生成后续情节
        continuation_templates = {
            0: f"{name}勇敢地迈出了第一步，虽然心里有点紧张，但是{name}知道做正确的事情很重要...",
            1: f"{name}仔细观察周围的情况，发现了一些重要的线索，这让{name}有了新的想法...",
            2: f"{name}意识到团结的力量，于是召集了更多的朋友，大家一起想办法...",
            3: f"{name}发挥了创造力，想出了一个前所未有的解决方案..."
        }
        
        continuation = continuation_templates.get(choice, continuation_templates[0])
        
        # 生成新的选择
        new_choices = [
            "继续这个计划",
            "尝试不同的方法",
            "寻求更多帮助"
        ]
        
        return {
            "story": continuation,
            "choices": new_choices,
            "story_progress": "continuing",
            "advanced_mode": False
        }

# 全局童话生成器实例
fairy_tale_generator = EnhancedFairyTaleGenerator()

@app.route('/')
def index():
    """主页"""
    return render_template('enhanced_index.html')

@app.route('/api/generate_story', methods=['POST'])
def generate_story():
    """生成故事API"""
    try:
        data = request.get_json()
        name = data.get('name', '小朋友')
        age = data.get('age', '6-8岁')
        theme = data.get('theme', '勇敢与友谊')
        interests = data.get('interests', '冒险,友谊')
        
        # 保存用户信息到session
        session['user_context'] = {
            'name': name,
            'age': age,
            'theme': theme,
            'interests': interests
        }
        
        # 生成故事
        result = fairy_tale_generator.generate_story(name, age, theme, interests)
        
        # 保存当前故事到session
        session['current_story'] = result['story']
        session['story_history'] = [result['story']]
        
        return jsonify({
            'success': True,
            'story': result['story'],
            'choices': result['choices'],
            'educational_value': result['educational_value'],
            'cognitive_level': result['cognitive_level']
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

@app.route('/api/make_choice', methods=['POST'])
def make_choice():
    """处理用户选择API"""
    try:
        data = request.get_json()
        choice_index = data.get('choice_index', 0)
        
        # 获取用户上下文
        context = session.get('user_context', {})
        previous_story = session.get('current_story', '')
        
        # 继续故事
        result = fairy_tale_generator.continue_story(previous_story, choice_index, context)
        
        # 更新session
        session['current_story'] = result['story']
        story_history = session.get('story_history', [])
        story_history.append(result['story'])
        session['story_history'] = story_history
        
        return jsonify({
            'success': True,
            'story': result['story'],
            'choices': result['choices'],
            'story_progress': result.get('story_progress', 'continuing')
        })
        
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        })

@app.route('/api/get_story_history')
def get_story_history():
    """获取故事历史"""
    history = session.get('story_history', [])
    return jsonify({
        'success': True,
        'history': history
    })

@app.route('/api/reset_story', methods=['POST'])
def reset_story():
    """重置故事"""
    session.clear()
    return jsonify({
        'success': True,
        'message': '故事已重置，可以开始新的冒险了！'
    })

@app.route('/health')
def health_check():
    """健康检查"""
    return jsonify({
        'status': 'healthy',
        'timestamp': datetime.now().isoformat(),
        'version': '1.0.0',
        'features': [
            'ERNIE-4.5-0.3B-Paddle集成',
            '智源研究院数据支撑',
            'MCP协议支持',
            '多模态交互',
            '个性化故事生成',
            '分支剧情系统'
        ]
    })

if __name__ == '__main__':
    print("🌟 启动智慧童话世界 - 增强版")
    print("📚 基于ERNIE-4.5-0.3B-Paddle + 智源研究院数据")
    print("🔗 集成MCP协议支持")
    print("🌐 访问地址: http://localhost:5000")
    print("=" * 50)
    
    # 创建templates目录
    os.makedirs('templates', exist_ok=True)
    
    app.run(debug=True, host='0.0.0.0', port=5000, threaded=True)